package io.yunho.srw.lean.webflux;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author: Jason
 * @date: 2021/5/12 9:46
 * @description:
 */
@RestController
@Slf4j
public class WebFluxController {
    @GetMapping("/common")
    public String common(){
        log.info("开始");
        String str = createStr();
        log.info("结束");
        return str;
    }

    private String createStr() {
        try {
            TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}
        return "哈哈";
    }

    @GetMapping("/mono")
    public Mono<String> monoDemo() {
        log.info("开始");
        Mono<String> mono = Mono.fromSupplier(() -> createStr());
        log.info("结束");
        return mono;
    }

    @GetMapping("/flux")
    //初次测试不指定返回格式
    public Flux<String> fluxDemo() {
        log.info("开始");
        Flux<String> flux = Flux.fromStream(IntStream.range(1,5).mapToObj(i->{
            try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}
            return "flux hello "+i;
        }));
        log.info("结束");
        return flux;
    }

    //指定flux返回格式
//    @GetMapping(value = "/fluxf",produces = "text/event-stream")
    @GetMapping(value = "/fluxf",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> fluxDemoFormat() {
        log.info("开始");
        Flux<String> flux = Flux.fromStream(IntStream.range(5,10).mapToObj(i->{
            try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            return "flux hello "+i;
        }));
        log.info("结束");
        return flux;
    }
}
